<template>
  <div class="spot-detail min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 页面头部 -->
    <div
      class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
    >
      <Breadcrumb
        :items="[
          { path: '/', title: '首页' },
          { path: '/spots', title: '景点导览' },
          { title: spotDetail.name || '景点详情' },
        ]"
      />
    </div>

    <!-- 顶部封面区域 -->
    <section class="spot-hero relative bg-gray-50 dark:bg-gray-800 py-8">
      <div class="container mx-auto px-4">
        <!-- 图片轮播 -->
        <div class="max-w-5xl mx-auto overflow-hidden rounded-xl shadow-lg">
          <el-carousel
            :interval="4000"
            height="400px"
            indicator-position="outside"
          >
            <el-carousel-item
              v-for="image in spotDetail.images"
              :key="image.id"
            >
              <el-image
                :src="image.url"
                fit="cover"
                class="w-full h-full"
                :preview-src-list="spotDetail.images.map((img) => img.url)"
              />
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 景点信息卡片 -->
        <div
          class="spot-info-card bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 max-w-4xl mx-auto mt-6 border border-gray-100 dark:border-gray-700"
        >
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
                {{ spotDetail.name }}
              </h1>
              <div class="mt-4 flex items-center space-x-6">
                <div class="rating-box">
                  <div class="flex items-center">
                    <span class="text-3xl font-bold text-primary-600">{{
                      spotDetail.rating
                    }}</span>
                    <span class="text-sm text-gray-500 dark:text-gray-400 ml-1"
                      >/ 5.0</span
                    >
                  </div>
                  <el-rate
                    v-model="spotDetail.rating"
                    disabled
                    :max="5"
                    allow-half
                    :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                    :void-icon="Star"
                    :void-color="'rgba(128,128,128,0.4)'"
                    show-score
                    :decimal-place="1"
                  />
                </div>
                <div class="stats-box space-y-1">
                  <div
                    class="flex items-center text-gray-600 dark:text-gray-300"
                  >
                    <el-icon><View /></el-icon>
                    <span class="ml-1"
                      >{{ formatNumber(spotDetail.viewCount) }}人去过</span
                    >
                  </div>
                  <div
                    class="flex items-center text-gray-600 dark:text-gray-300"
                  >
                    <el-icon><Timer /></el-icon>
                    <span class="ml-1"
                      >建议游玩 {{ spotDetail.suggestedTime }}</span
                    >
                  </div>
                </div>
                <div class="tags-box">
                  <el-tag
                    v-for="tag in spotDetail.tags"
                    :key="tag"
                    :type="getTagType(tag)"
                    class="mr-2"
                    size="small"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div class="action-buttons space-x-2">
              <el-button type="primary" size="large" @click="isFreeSpot ? openInMap() : handleBookTicket()">
                <el-icon>
                  <template v-if="isFreeSpot"><Position /></template>
                  <template v-else><Ticket /></template>
                </el-icon>
                {{ isFreeSpot ? '前往景点' : '立即预订' }}
              </el-button>
              <el-button type="primary" plain size="large" @click="handleShare">
                <el-icon><Share /></el-icon>
                分享
              </el-button>
              <el-button
                :type="spotDetail.isFavorited ? 'primary' : 'default'"
                plain
                size="large"
                @click="handleFavorite"
              >
                <el-icon><Star /></el-icon>
                {{ spotDetail.isFavorited ? "已收藏" : "收藏" }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="content-wrapper grid grid-cols-12 gap-8">
        <!-- 左侧主要内容 -->
        <div class="main-content col-span-12 lg:col-span-8 space-y-8">
          <!-- 快速导航 -->
          <nav class="quick-nav">
            <el-affix :offset="60">
              <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
                <el-scrollbar class="nav-scrollbar">
                  <div class="flex space-x-6">
                    <a
                      v-for="nav in quickNavs"
                      :key="nav.id"
                      :href="'#' + nav.id"
                      class="nav-item text-gray-600 dark:text-gray-300 hover:text-primary-600 dark:hover:text-primary-400 relative no-underline"
                      :class="{ active: currentSection === nav.id }"
                    >
                      {{ nav.title }}
                    </a>
                  </div>
                </el-scrollbar>
              </div>
            </el-affix>
          </nav>

          <!-- 景点简介 -->
          <section id="intro" class="content-section">
            <div class="section-header">
              <h2 class="section-title text-gray-900 dark:text-white">
                景点简介
              </h2>
            </div>
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
              <article class="prose prose-gray dark:prose-invert max-w-none">
                {{ spotDetail.introduction }}
              </article>
            </div>
          </section>

          <!-- 开放信息 -->
          <section id="info" class="content-section">
            <div class="section-header">
              <h2 class="section-title text-gray-900 dark:text-white">
                开放信息
              </h2>
            </div>
            <div class="info-grid grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- 开放时间卡片 -->
              <div
                class="info-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
              >
                <div class="card-header flex items-center space-x-3 mb-4">
                  <el-icon
                    class="text-primary-600 dark:text-primary-400 text-xl"
                    ><Clock
                  /></el-icon>
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    开放时间
                  </h3>
                </div>
                <div class="time-info space-y-2">
                  <p class="text-gray-600 dark:text-gray-300">
                    {{ spotDetail.openTime }}
                  </p>
                  <p class="text-sm text-gray-500 dark:text-gray-400">
                    建议游玩: {{ spotDetail.suggestedTime }}
                  </p>
                  <div
                    class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700"
                  >
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      高峰时段提醒
                    </div>
                    <p class="text-gray-600 dark:text-gray-300 mt-1">
                      {{ spotDetail.peakHours || "周末及节假日 9:00-16:00" }}
                    </p>
                  </div>
                </div>
              </div>

              <!-- 天气信息卡片 -->
              <div
                class="info-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
              >
                <div class="card-header flex items-center space-x-3 mb-4">
                  <sunny
                    theme="filled"
                    size="24"
                    class="text-primary-600 dark:text-primary-400"
                  />
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    天气信息
                  </h3>
                </div>
                <div class="weather-info">
                  <div class="current-weather flex items-start">
                    <div
                      class="weather-icon mr-6 flex items-center justify-center bg-gradient-to-br from-blue-400 to-blue-600 dark:from-blue-500 dark:to-blue-700 rounded-2xl w-24 h-24"
                    >
                      <component
                        :is="getWeatherIcon"
                        theme="filled"
                        :size="64"
                        class="text-white"
                      />
                    </div>
                    <div class="weather-details flex-1">
                      <div class="temperature-info mb-2">
                        <span
                          class="text-4xl font-medium text-gray-900 dark:text-white"
                          >{{ spotDetail.weather?.temperature || "25°C" }}</span
                        >
                        <span
                          class="text-lg text-gray-600 dark:text-gray-300 ml-2"
                          >{{ spotDetail.weather?.condition || "晴" }}</span
                        >
                      </div>
                      <div class="weather-meta grid grid-cols-3 gap-4 mt-4">
                        <div
                          class="weather-meta-item text-center p-2 rounded-lg bg-gray-50 dark:bg-gray-700"
                        >
                          <div class="text-sm text-gray-500 dark:text-gray-400">
                            空气质量
                          </div>
                          <div
                            class="text-base font-medium mt-1"
                            :class="getAirQualityClass"
                          >
                            {{ spotDetail.weather?.airQuality || "优" }}
                          </div>
                        </div>
                        <div
                          class="weather-meta-item text-center p-2 rounded-lg bg-gray-50 dark:bg-gray-700"
                        >
                          <div class="text-sm text-gray-500 dark:text-gray-400">
                            相对湿度
                          </div>
                          <div
                            class="text-base font-medium mt-1 text-gray-900 dark:text-white"
                          >
                            {{ spotDetail.weather?.humidity || "65%" }}
                          </div>
                        </div>
                        <div
                          class="weather-meta-item text-center p-2 rounded-lg bg-gray-50 dark:bg-gray-700"
                        >
                          <div class="text-sm text-gray-500 dark:text-gray-400">
                            紫外线
                          </div>
                          <div
                            class="text-base font-medium mt-1 text-gray-900 dark:text-white"
                          >
                            {{ spotDetail.weather?.uvIndex || "中等" }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    class="weather-tips mt-4 pt-4 border-t border-gray-100 dark:border-gray-700"
                  >
                    <p class="text-sm text-gray-600 dark:text-gray-300">
                      <info-filled
                        theme="filled"
                        size="16"
                        class="mr-1 text-primary-600 dark:text-primary-400"
                      />
                      {{
                        spotDetail.weather?.tips ||
                        "天气适宜游玩，建议戴好遮阳帽，注意防晒"
                      }}
                    </p>
                  </div>
                </div>
              </div>

              <!-- 交通位置卡片 -->
              <div
                class="info-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
              >
                <div class="card-header flex items-center space-x-3 mb-4">
                  <el-icon
                    class="text-primary-600 dark:text-primary-400 text-xl"
                    ><Location
                  /></el-icon>
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    交通位置
                  </h3>
                </div>
                <div class="location-info space-y-4">
                  <div class="address-info">
                    <p class="text-gray-600 dark:text-gray-300 flex items-start">
                      <span class="flex-shrink-0 inline-block w-20 text-gray-500 dark:text-gray-400">详细地址:</span>
                      <span>{{ spotDetail.address }}</span>
                    </p>
                    <el-button
                      type="primary"
                      link
                      class="mt-1 ml-20 p-0 dark:text-primary-400"
                      @click="handleCopyAddress"
                    >
                      <el-icon><CopyDocument /></el-icon>
                      <span class="ml-1">复制地址</span>
                    </el-button>
                  </div>
                  <div class="transportation-info space-y-3">
                    <div class="transport-item">
                      <div
                        class="flex items-center text-sm text-gray-500 dark:text-gray-400 mb-1"
                      >
                        <el-icon class="mr-1 text-primary-500"><Van /></el-icon>
                        公交路线
                      </div>
                      <p class="text-gray-600 dark:text-gray-300 ml-5 bg-gray-50 dark:bg-gray-700 p-2 rounded">
                        {{
                          spotDetail.transportation?.bus ||
                          "推荐乘坐前往附近的公交线路，详情可咨询当地公交部门"
                        }}
                      </p>
                    </div>
                    <div class="transport-item">
                      <div
                        class="flex items-center text-sm text-gray-500 dark:text-gray-400 mb-1"
                      >
                        <el-icon class="mr-1 text-primary-500"><Guide /></el-icon>
                        自驾路线
                      </div>
                      <p class="text-gray-600 dark:text-gray-300 ml-5 bg-gray-50 dark:bg-gray-700 p-2 rounded">
                        {{
                          spotDetail.transportation?.drive ||
                          "导航至\"\"，详细位置可咨询景区"
                        }}
                      </p>
                    </div>
                    <div class="transport-item">
                      <div
                        class="flex items-center text-sm text-gray-500 dark:text-gray-400 mb-1"
                      >
                        <el-icon class="mr-1 text-primary-500"><LocationInformation /></el-icon>
                        停车信息
                      </div>
                      <p class="text-gray-600 dark:text-gray-300 ml-5 bg-gray-50 dark:bg-gray-700 p-2 rounded">
                        {{
                          spotDetail.transportation?.parking ||
                          "附近有停车场，建议提前规划"
                        }}
                      </p>
                    </div>
                  </div>
                  <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
                    <el-button 
                      type="primary" 
                      plain 
                      icon="Position" 
                      @click="openInMap" 
                      class="w-full"
                    >
                      在地图中打开
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 实时客流信息 -->
              <div
                class="info-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-100 dark:border-gray-700"
              >
                <div class="card-header flex items-center space-x-3 mb-4">
                  <el-icon
                    class="text-primary-600 dark:text-primary-400 text-xl"
                    ><PieChart
                  /></el-icon>
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    实时客流
                  </h3>
                </div>
                <SpotRealtime />
              </div>
            </div>
          </section>

          <!-- 景点特色 -->
          <section id="features" class="content-section">
            <div class="section-header">
              <h2 class="section-title text-gray-900 dark:text-white">
                景点特色
              </h2>
            </div>
            <div class="features-grid grid gap-6">
              <div
                v-for="feature in spotDetail.features"
                :key="feature.title"
                class="feature-card bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden"
              >
                <el-image
                  v-if="feature.image"
                  :src="feature.image"
                  fit="cover"
                  class="w-full h-48 object-cover"
                />
                <div class="p-6">
                  <h3
                    class="text-xl font-medium mb-3 text-gray-900 dark:text-white"
                  >
                    {{ feature.title }}
                  </h3>
                  <p class="text-gray-600 dark:text-gray-300">
                    {{ feature.description }}
                  </p>
                </div>
              </div>
            </div>
          </section>

          <!-- 游客评价 -->
          <section id="reviews" class="content-section">
            <div class="section-header flex items-center justify-between">
              <h2 class="section-title text-gray-900 dark:text-white">
                游客评价
              </h2>
            </div>
            <div
              class="reviews-overview bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
            >
              <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="overall-rating text-center">
                  <div
                    class="rating-score text-4xl font-bold text-primary-600 dark:text-primary-400"
                  >
                    {{ spotDetail.rating }}
                  </div>
                  <el-rate v-model="spotDetail.rating" disabled />
                  <div
                    class="rating-count text-sm text-gray-500 dark:text-gray-400 mt-2"
                  >
                    {{ spotDetail.reviewCount }}条点评
                  </div>
                </div>
                <div class="rating-tags col-span-2">
                  <div class="tags-grid grid grid-cols-2 gap-3">
                    <div
                      v-for="tag in spotDetail.reviewTags"
                      :key="tag.name"
                      class="tag-item flex items-center justify-between p-2 rounded-lg bg-gray-50 dark:bg-gray-700"
                    >
                      <span class="tag-name text-gray-600 dark:text-gray-300">{{
                        tag.name
                      }}</span>
                      <span
                        class="tag-count text-primary-600 dark:text-primary-400"
                        >{{ tag.count }}</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 评价列表 -->
            <div class="reviews-list space-y-4">
              <CommentSection
                :comments="spotDetail.reviews"
                :current-user="currentUser"
                :loading="false"
                :has-more="hasMoreReviews"
                :total-comments="spotDetail.reviewCount"
                :button-style="'arco'"
                :show-favorite="false"
                @submit="handleReviewSubmit"
                @like="handleReviewLike"
                @load-more="loadMoreReviews"
              />
            </div>
          </section>
        </div>

        <!-- 右侧边栏 -->
        <div class="side-content col-span-12 lg:col-span-4 space-y-6">
          <!-- 门票预订卡片 -->
          <div class="sticky top-6">
            <div
              class="ticket-card bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden"
            >
              <div class="card-header bg-primary-50 dark:bg-primary-900/30 p-4">
                <h3
                  class="text-lg font-medium text-primary-900 dark:text-primary-100"
                >
                  {{ isFreeSpot ? '景点信息' : '门票预订' }}
                </h3>
                <p class="text-sm text-primary-600 dark:text-primary-400 mt-1">
                  {{ isFreeSpot ? '欢迎光临，免费畅玩' : '预订门票享受优惠价格' }}
                </p>
              </div>
              <div class="card-body p-4">
                <div v-if="isFreeSpot" class="p-4 text-center">
                  <div class="text-3xl font-bold text-primary-600 dark:text-primary-400 mb-2">免费开放</div>
                  <p class="text-gray-600 dark:text-gray-300 mb-4">{{spotDetail.openTime}}</p>
                  <el-button
                    type="primary"
                    class="w-full"
                    icon="Position"
                    @click="openInMap"
                  >
                    前往景点
                  </el-button>
                </div>
                <div v-else class="ticket-list space-y-4">
                  <div
                    v-for="ticket in spotDetail.tickets"
                    :key="ticket.id"
                    class="ticket-item border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-primary-300 dark:hover:border-primary-500 transition-colors"
                  >
                    <div class="flex items-start justify-between mb-2">
                      <div>
                        <h4 class="font-medium text-gray-900 dark:text-white">
                          {{ ticket.name }}
                        </h4>
                        <p class="text-sm text-gray-500 dark:text-gray-400">
                          {{ ticket.description }}
                        </p>
                      </div>
                      <div class="text-right">
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                          门市价
                        </div>
                        <div
                          class="text-lg font-medium text-primary-600 dark:text-primary-400"
                        >
                          ¥{{ ticket.price }}
                        </div>
                      </div>
                    </div>
                    <el-button
                      type="primary"
                      class="w-full"
                      @click="handleBookTicket(ticket)"
                    >
                      立即预订
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 周边推荐 -->
            <div
              class="nearby-card bg-white dark:bg-gray-800 rounded-lg shadow-sm mt-6"
            >
              <div
                class="card-header p-4 border-b border-gray-100 dark:border-gray-700"
              >
                <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                  周边推荐
                </h3>
              </div>
              <div class="card-body p-4">
                <div class="nearby-list space-y-4">
                  <div
                    v-for="spot in spotDetail.nearbySpots"
                    :key="spot.id"
                    class="nearby-item group cursor-pointer"
                    @click="router.push('/spots/' + spot.id)"
                  >
                    <div class="flex space-x-3">
                      <el-image
                        :src="spot.cover"
                        fit="cover"
                        class="w-20 h-20 rounded-lg object-cover group-hover:ring-2 ring-primary-500 transition-all"
                      />
                      <div class="flex-1 min-w-0">
                        <h4
                          class="font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors"
                        >
                          {{ spot.name }}
                        </h4>
                        <div
                          class="mt-1 flex items-center text-sm text-gray-500 dark:text-gray-400"
                        >
                          <el-icon><Location /></el-icon>
                          <span class="ml-1">距离{{ spot.distance }}公里</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <ShareDialog
      v-model="shareDialogVisible"
      :content="shareContent"
      @share="handleShare"
    />

    <!-- 评论弹窗 -->
    <el-dialog v-model="reviewDialogVisible" title="写点评" width="600px">
      <ReviewForm
        :spot-id="spotDetail.id"
        @submit="handleReviewSubmit"
        @cancel="reviewDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Location,
  View,
  Share,
  Clock,
  PieChart,
  Timer,
  Ticket,
  CopyDocument,
  Back,
  Star,
  Van,
  Guide,
  LocationInformation,
  Position
} from "@element-plus/icons-vue";
import {
  Sunny,
  Cloudy,
  ThunderstormOne,
  Moon,
  MoonlightCloudy,
  Sunrise,
  Sunset,
  LightRain,
  HeavyRain,
  Fog,
  InfoFilled,
} from "@icon-park/vue-next";
import SpotRealtime from "@/components/spots/SpotRealtime.vue";
import ShareDialog from "@/components/global/ShareDialog.vue";
import ReviewForm from "@/components/spots/ReviewForm.vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import CommentSection from "@/components/spots/CommentSection.vue";
import service from "@/api/axios"; // 导入axios实例

// 路由相关
const router = useRouter();
const route = useRoute();

// 共享相关
const shareDialogVisible = ref(false);
const shareContent = ref({});

// 判断是否为免费景点
const isFreeSpot = computed(() => {
  // 如果价格明确为0，则一定是免费景点
  if (spotDetail.value.price === 0) {
    return true;
  }
  
  // 如果没有门票数据或所有门票价格为0，则视为免费景点
  if (!spotDetail.value.tickets || spotDetail.value.tickets.length === 0) {
    return true;
  }
  
  // 检查是否所有门票价格都为0
  return spotDetail.value.tickets.every(ticket => !ticket.price || ticket.price === 0);
});

// 处理分享
const handleShare = () => {
  shareContent.value = {
    title: spotDetail.value.name,
    description: spotDetail.value.introduction,
    image: spotDetail.value.images[0]?.url,
    url: window.location.href,
  };
  shareDialogVisible.value = true;
};

const hasMoreReviews = ref(false);
const currentUser = ref({
  id: 1,
  name: "游客",
  avatar: "/images/avatars/default.jpg",
});

// 景点详情数据
const spotDetail = ref({
  id: 1,
  name: "贵港江滨公园",
  rating: 4.5,
  viewCount: 12345,
  price: 68,
  introduction:
    "贵港江滨公园位于邕江畔，是一个集观光、休闲、娱乐为一体的综合性公园。公园内绿树成荫，花草繁茂，是市民休闲娱乐的好去处。",
  tags: ["网红打卡", "亲子游玩", "自然风光", "休闲娱乐"],
  openTime: "全天开放",
  suggestedTime: "2-3小时",
  address: "广西贵港市港北区江滨路1号",
  transportation: {
    bus: "推荐乘坐前往附近的公交线路，详情可咨询当地公交部门",
    drive: "导航至\"\"，详细位置可咨询景区",
    parking: "附近有停车场，建议提前规划"
  },
  images: [
    { id: 1, url: "/images/spots/spot1-1.jpg" },
    { id: 2, url: "/images/spots/spot1-2.jpg" },
    { id: 3, url: "/images/spots/spot1-3.jpg" },
  ],
  features: [
    {
      title: "江景观光",
      description: "沿江步道全长2公里，可欣赏邕江美景和城市天际线。",
      image: "/images/spots/feature1.jpg",
    },
    {
      title: "休闲广场",
      description: "设有大型休闲广场，是市民跳广场舞、晨练的好去处。",
      image: "/images/spots/feature2.jpg",
    },
  ],
  reviewCount: 1234,
  reviewTags: [
    { name: "环境优美", count: 532, type: "success" },
    { name: "交通便利", count: 423, type: "primary" },
    { name: "设施完善", count: 321, type: "warning" },
  ],
  reviews: [],
  tickets: [
    {
      id: 1,
      name: "成人票",
      price: 68,
      description: "含景区内所有游玩项目",
    },
    {
      id: 2,
      name: "儿童票",
      price: 38,
      description: "1.2米以下儿童享受优惠",
    },
  ],
  nearbySpots: [
    {
      id: 2,
      name: "贵港古镇",
      cover: "/images/spots/spot2.jpg",
      distance: 3.5,
    },
  ],
  weather: {
    temperature: "25°C",
    condition: "晴",
    airQuality: "优",
    humidity: "65%",
    uvIndex: "中等",
    tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒",
  },
  peakHours: "周末及节假日 9:00-16:00",
  isFavorited: false,
});

// 获取景点详情
const getSpotDetail = async () => {
  try {
    // 调用API获取景点详情
    const res = await service.get(`/public/spot/${route.params.id}`);
    console.log("景点详情API响应:", res);
    
    // 根据API返回的数据结构判断
    if (res.data && res.data.code === 200 && res.data.data) {
      console.log("成功获取景点数据，使用后端返回数据");
      
      // 使用后端嵌套结构的数据
      const apiData = res.data.data;
      
      // 创建一个新对象，包含处理过的字段
      const processedData = {
        id: apiData.id,
        name: apiData.name,
        introduction: apiData.description || "",
        rating: apiData.rating || 4.5,
        viewCount: apiData.stats?.visits || 1000,
        price: apiData.price || 0,
        tags: apiData.category ? apiData.category.split("、") : ["自然风光"],
        openTime: (apiData.notice && apiData.notice.match(/开放时间：(.+)/)) 
          ? apiData.notice.match(/开放时间：(.+)/)[1] 
          : "全天开放",
        suggestedTime: "2-3小时",
        address: apiData.address || "",
        transportation: {
          bus: apiData.trafficGuide?.match(/公交：(.+)/) 
            ? apiData.trafficGuide.match(/公交：(.+)/)[1] 
            : "推荐乘坐公交前往",
          drive: apiData.trafficGuide?.match(/自驾：(.+)/) 
            ? apiData.trafficGuide.match(/自驾：(.+)/)[1] 
            : "导航至景区",
          parking: "附近有停车场，详情可咨询景区"
        },
        // 处理图片 - 根据接口文档，images字段是字符串数组
        images: Array.isArray(apiData.images) 
          ? apiData.images.map((url, index) => ({
              id: index + 1,
              url: url
            }))
          : [{
              id: 1,
              url: apiData.coverImage || "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"
            }],
        // 处理特色
        features: apiData.features 
          ? apiData.features.split("、").map((feature, index) => ({
              title: feature,
              description: `${apiData.name}的${feature}特色景观`,
              image: Array.isArray(apiData.images) && apiData.images[index] 
                ? apiData.images[index] 
                : apiData.coverImage
            }))
          : [{
              title: "景区特色",
              description: apiData.description || "暂无特色描述",
              image: apiData.coverImage
            }],
        // 其他信息
        reviews: [],
        reviewCount: 0,
        tickets: [{
          id: 1,
          name: apiData.price > 0 ? "成人票" : "免费门票",
          price: apiData.price || 0,
          description: apiData.price > 0 ? "含景区内所有游玩项目" : "免费开放，无需门票"
        }],
        nearbySpots: [],
        weather: {
          temperature: "25°C",
          condition: "晴",
          airQuality: "优",
          humidity: "65%",
          uvIndex: "中等",
          tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
        },
        peakHours: "周末及节假日 9:00-18:00",
        isFavorited: false,
        // 额外的字段 - 存储纬度和经度用于地图
        longitude: apiData.longitude,
        latitude: apiData.latitude,
        // 保存原始数据以备后用
        rawData: apiData
      };
      
      console.log("处理后的景点数据:", processedData);
      console.log("图片数据:", processedData.images);
      
      // 使用处理后的数据
      spotDetail.value = processedData;
      
      // 获取附近景点
      getNearbySpots();
      
      // 获取评论
      getReviews();
      
      // 获取天气信息
      getWeatherInfo();
      
      // 获取交通信息
      getTransportationInfo();
    } 
    // 处理直接返回数据的结构 (非嵌套code/data结构)
    else if (res.data && res.data.id) {
      console.log("成功获取景点数据，使用非嵌套结构的后端返回数据");
      
      const apiData = res.data;
      
      // 创建一个新对象，包含处理过的字段
      const processedData = {
        id: apiData.id,
        name: apiData.name,
        introduction: apiData.description || apiData.introduction || "",
        rating: apiData.rating || 4.5,
        viewCount: apiData.viewCount || apiData.view_count || apiData.stats?.visits || 1000,
        price: apiData.price || 0,
        tags: apiData.tags || apiData.category?.split("、") || ["自然风光"],
        openTime: apiData.openTime || apiData.open_time || "全天开放",
        suggestedTime: apiData.suggestedTime || apiData.suggested_time || "2-3小时",
        address: apiData.address || "",
        transportation: apiData.transportation || {
          bus: apiData.bus || "推荐乘坐前往附近的公交线路，详情可咨询当地公交部门",
          drive: apiData.drive || "导航至景区",
          parking: apiData.parking || "附近有停车场，建议提前规划"
        },
        // 处理图片
        images: apiData.images 
          ? (Array.isArray(apiData.images) 
             ? (typeof apiData.images[0] === 'string' 
                // 如果是字符串数组，转换为对象数组
                ? apiData.images.map((url, index) => ({
                    id: index + 1,
                    url: url
                  }))
                // 如果已经是对象数组，确保格式正确
                : apiData.images.map((img, index) => ({
                    id: img.id || index + 1,
                    url: img.url || img.image_url || img.imageUrl || img
                  }))
              )
             : [{
                 id: 1,
                 url: apiData.coverImage || apiData.cover_image || "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"
               }]
          )
          : [{
              id: 1,
              url: apiData.coverImage || apiData.cover_image || "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"
            }],
        // 其他数据处理...
        // 剩余代码保持不变
        features: apiData.features 
          ? (typeof apiData.features === 'string' 
             ? apiData.features.split("、").map((feature, index) => ({
                 title: feature,
                 description: `${apiData.name}的${feature}特色景观`,
                 image: Array.isArray(apiData.images) 
                   ? (typeof apiData.images[0] === 'string'
                      ? apiData.images[index % apiData.images.length] || apiData.coverImage
                      : apiData.images[index % apiData.images.length]?.url || apiData.coverImage)
                   : apiData.coverImage
               }))
             : apiData.features
          )
          : [{
              title: "景区特色",
              description: apiData.description || "暂无特色描述",
              image: apiData.coverImage || apiData.cover_image
            }],
        // 其他信息
        reviews: apiData.reviews || [],
        reviewCount: apiData.reviewCount || 0,
        tickets: apiData.tickets || [{
          id: 1,
          name: apiData.price > 0 ? "成人票" : "免费门票",
          price: apiData.price || 0,
          description: apiData.price > 0 ? "含景区内所有游玩项目" : "免费开放，无需门票"
        }],
        nearbySpots: apiData.nearbySpots || [],
        weather: apiData.weather || {
          temperature: "25°C",
          condition: "晴",
          airQuality: "优",
          humidity: "65%",
          uvIndex: "中等",
          tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
        },
        peakHours: apiData.peakHours || "周末及节假日 9:00-18:00",
        isFavorited: apiData.isFavorited || false,
        // 额外的字段 - 存储纬度和经度用于地图
        longitude: apiData.longitude,
        latitude: apiData.latitude,
        // 保存原始数据以备后用
        rawData: apiData
      };
      
      // 处理门票信息 - 确保价格为0的票显示为免费
      if (processedData.price === 0) {
        // 如果景点本身价格为0，确保它被识别为免费景点
        if (processedData.tickets && processedData.tickets.length > 0) {
          processedData.tickets = processedData.tickets.map(ticket => {
            // 将所有价格设为0
            ticket.price = 0;
            // 描述更新为免费
            if (!ticket.description || !ticket.description.includes('免费')) {
              ticket.description = '免费开放，无需门票';
            }
            return ticket;
          });
        } else {
          // 创建一个默认免费门票
          processedData.tickets = [{
            id: 1,
            name: "免费门票",
            price: 0,
            description: "免费开放，无需门票"
          }];
        }
      }
      
      console.log("处理后的景点数据:", processedData);
      console.log("图片数据:", processedData.images);
      
      // 使用处理后的数据
      spotDetail.value = processedData;
      
      // 获取附近景点
      getNearbySpots();
      
      // 获取评论
      getReviews();
      
      // 获取天气信息
      getWeatherInfo();
      
      // 获取交通信息
      getTransportationInfo();
    }
    else {
      console.log("景点详情API请求返回无效数据，使用测试数据");
      console.log("res.data:", res.data);
      // 使用测试数据，但使用线上图片地址
      spotDetail.value = {
        id: route.params.id,
        name: "贵港江滨公园",
        rating: 4.5,
        viewCount: 12345,
        price: 0,  // 设置为免费
        introduction: "贵港江滨公园位于邕江畔，是一个集观光、休闲、娱乐为一体的综合性公园。公园内绿树成荫，花草繁茂，是市民休闲娱乐的好去处。",
        tags: ["网红打卡", "亲子游玩", "自然风光", "休闲娱乐"],
        openTime: "全天开放",
        suggestedTime: "2-3小时",
        address: "广西贵港市港北区江滨路1号",
        transportation: {
          bus: "推荐乘坐前往附近的公交线路，详情可咨询当地公交部门",
          drive: "导航至景区",
          parking: "附近有停车场，建议提前规划"
        },
        // 使用线上图片地址替代本地资源
        images: [
          { id: 1, url: "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
          { id: 2, url: "https://img2.baidu.com/it/u=358809126,2038860615&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
          { id: 3, url: "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
        ],
        features: [
          {
            title: "江景观光",
            description: "沿江步道全长2公里，可欣赏邕江美景和城市天际线。",
            image: "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
          },
          {
            title: "休闲广场",
            description: "设有大型休闲广场，是市民跳广场舞、晨练的好去处。",
            image: "https://img2.baidu.com/it/u=358809126,2038860615&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
          },
        ],
        reviewCount: 2,
        reviewTags: [
          { name: "环境优美", count: 532, type: "success" },
          { name: "交通便利", count: 423, type: "primary" },
          { name: "设施完善", count: 321, type: "warning" },
        ],
        reviews: [
          {
            id: 1,
            content: "环境优美，空气清新，非常适合周末带孩子来玩。",
            rating: 5,
            createdAt: "2023-05-10 10:20:00",
            likes: 23,
            isLiked: false,
            images: [],
            location: "贵港",
            user: {
              id: 101,
              name: "清风徐来",
              avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Felix&backgroundColor=b6e3f4"
            },
            replies: []
          },
          {
            id: 2,
            content: "人不多，景色优美，是休闲的好去处。就是卫生间有点少，建议增加一些。",
            rating: 4,
            createdAt: "2023-05-10 15:40:00",
            likes: 15,
            isLiked: true,
            images: [],
            location: "贵港",
            user: {
              id: 102,
              name: "漫步云端",
              avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Luna&backgroundColor=ffdfbf"
            },
            replies: [
              {
                id: 101,
                content: "同意，上次去卫生间排了好久的队",
                createdAt: "2023-05-11 08:15:00",
                user: {
                  id: 103,
                  name: "城市观察家",
                  avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Max&backgroundColor=d1d4f9"
                }
              }
            ]
          }
        ],
        tickets: [{
          id: 1,
          name: "免费门票",
          price: 0,
          description: "免费开放，无需门票"
        }],
        nearbySpots: [
          {
            id: 2,
            name: "贵港古镇",
            cover: "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
            distance: 3.5,
          }
        ],
        weather: {
          temperature: "25°C",
          condition: "晴",
          airQuality: "优",
          humidity: "65%",
          uvIndex: "中等",
          tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
        },
        peakHours: "周末及节假日 9:00-16:00",
        isFavorited: false,
      };
      
      // 获取评论 - 即使使用测试数据也尝试获取真实评论
      getReviews();
    }
  } catch (error) {
    console.error("获取景点详情失败:", error);
    // 使用测试数据，但使用线上图片地址
    spotDetail.value = {
      id: route.params.id,
      name: "贵港江滨公园",
      rating: 4.5,
      viewCount: 12345,
      price: 0,  // 设置为免费
      introduction: "贵港江滨公园位于邕江畔，是一个集观光、休闲、娱乐为一体的综合性公园。公园内绿树成荫，花草繁茂，是市民休闲娱乐的好去处。",
      tags: ["网红打卡", "亲子游玩", "自然风光", "休闲娱乐"],
      openTime: "全天开放",
      suggestedTime: "2-3小时",
      address: "广西贵港市港北区江滨路1号",
      transportation: {
        bus: "推荐乘坐前往附近的公交线路，详情可咨询当地公交部门",
        drive: "导航至景区",
        parking: "附近有停车场，建议提前规划"
      },
      // 使用线上图片地址替代本地资源
      images: [
        { id: 1, url: "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
        { id: 2, url: "https://img2.baidu.com/it/u=358809126,2038860615&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
        { id: 3, url: "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" },
      ],
      features: [
        {
          title: "江景观光",
          description: "沿江步道全长2公里，可欣赏邕江美景和城市天际线。",
          image: "https://img0.baidu.com/it/u=2028084904,3939093125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
        },
        {
          title: "休闲广场",
          description: "设有大型休闲广场，是市民跳广场舞、晨练的好去处。",
          image: "https://img2.baidu.com/it/u=358809126,2038860615&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
        },
      ],
      reviewCount: 0,
      reviewTags: [
        { name: "环境优美", count: 532, type: "success" },
        { name: "交通便利", count: 423, type: "primary" },
        { name: "设施完善", count: 321, type: "warning" },
      ],
      reviews: [],
      tickets: [{
        id: 1,
        name: "免费门票",
        price: 0,
        description: "免费开放，无需门票"
      }],
      nearbySpots: [
        {
          id: 2,
          name: "贵港古镇",
          cover: "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
          distance: 3.5,
        }
      ],
      weather: {
        temperature: "25°C",
        condition: "晴",
        airQuality: "优",
        humidity: "65%",
        uvIndex: "中等",
        tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
      },
      peakHours: "周末及节假日 9:00-16:00",
      isFavorited: false,
    };
  }
};

// 处理门票预订
const handleBookTicket = (ticket) => {
  // 如果未提供门票，默认使用第一张门票
  if (!ticket && spotDetail.value.tickets && spotDetail.value.tickets.length > 0) {
    ticket = spotDetail.value.tickets[0];
  }
  
  // 如果没有门票数据，显示提示并返回
  if (!ticket) {
    ElMessage.warning('暂无可预订的门票');
    return;
  }
  
  router.push({
    path: "/order/confirm",
    query: {
      type: "ticket",
      data: encodeURIComponent(
        JSON.stringify({
          spotId: spotDetail.value.id,
          spotName: spotDetail.value.name,
          spotImage: spotDetail.value.images[0]?.url,
          ticketId: ticket.id,
          ticketName: ticket.name,
          price: ticket.price,
          description: ticket.description,
        }),
      ),
    },
  });
};

// 处理收藏
const handleFavorite = async () => {
  try {
    // 检查用户是否登录
    if (!localStorage.getItem('token')) {
      ElMessage.warning('请先登录后再收藏');
      return;
    }
    
    // 调用收藏/取消收藏API
    const url = spotDetail.value.isFavorited ? '/spot/uncollect' : '/spot/collect';
    await service.post(url, { spotId: spotDetail.value.id });
    
    spotDetail.value.isFavorited = !spotDetail.value.isFavorited;
    ElMessage.success(spotDetail.value.isFavorited ? "收藏成功" : "取消收藏");
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

// 处理评论提交
const handleReviewSubmit = async (review) => {
  try {
    // 检查用户是否登录
    if (!localStorage.getItem('token')) {
      ElMessage.warning('请先登录后再评论');
      return;
    }
    
    // 添加景点ID
    review.spotId = spotDetail.value.id;
    
    // 提交评论
    await service.post('/spot/review', review);
    
    // 关闭评论对话框
    reviewDialogVisible.value = false;
    
    // 刷新评论列表
    getReviews();
    
    ElMessage.success("评论提交成功");
  } catch (error) {
    console.error("评论提交失败:", error);
    ElMessage.error("评论提交失败，请重试");
  }
};

// 处理评论点赞
const handleReviewLike = async (review) => {
  try {
    // 检查用户是否登录
    if (!localStorage.getItem('token')) {
      ElMessage.warning('请先登录后再点赞');
      return;
    }
    
    // 调用点赞API
    await service.post('/spot/review/like', { reviewId: review.id });
    
    // 更新点赞状态和数量
    review.isLiked = !review.isLiked;
    review.likes += review.isLiked ? 1 : -1;
    
    ElMessage.success("点赞成功");
  } catch (error) {
    console.error("点赞失败:", error);
    ElMessage.error("点赞失败，请重试");
  }
};

// 加载更多评论
const loadMoreReviews = async () => {
  try {
    const nextPage = Math.ceil(spotDetail.value.reviews.length / 10) + 1;
    const res = await service.get(`/public/spot/reviews/${route.params.id}`, {
      params: {
        page: nextPage,
        pageSize: 10
      }
    });
    console.log("加载更多评论API响应:", res);
    
    if (res.data && res.data.code === 200) {
      const apiData = res.data.data;
      
      if (apiData && apiData.records && Array.isArray(apiData.records)) {
        // 处理分页数据，确保每条评论都有必要的属性
        const formattedReviews = apiData.records.map(review => {
          return {
            id: review.id,
            content: review.content || "用户未填写评价内容",
            rating: review.rating || 5,
            createdAt: review.createdAt || review.createTime || new Date().toISOString(),
            likes: review.likes || 0,
            isLiked: review.isLiked || false,
            images: review.images || [],
            location: review.location || "贵港",
            user: {
              id: review.userId || review.user?.id || 0,
              name: review.userName || review.user?.name || "游客",
              avatar: review.userAvatar || review.user?.avatar || "/images/avatars/default.jpg"
            },
            replies: review.replies || []
          };
        });
        
        spotDetail.value.reviews = [...spotDetail.value.reviews, ...formattedReviews];
        hasMoreReviews.value = spotDetail.value.reviews.length < apiData.total;
      } else if (Array.isArray(apiData)) {
        // 处理数组形式的API数据
        const formattedReviews = apiData.map(review => {
          return {
            id: review.id,
            content: review.content || "用户未填写评价内容",
            rating: review.rating || 5,
            createdAt: review.createdAt || review.createTime || new Date().toISOString(),
            likes: review.likes || 0,
            isLiked: review.isLiked || false,
            images: review.images || [],
            location: review.location || "贵港",
            user: {
              id: review.userId || review.user?.id || 0,
              name: review.userName || review.user?.name || "游客",
              avatar: review.userAvatar || review.user?.avatar || "/images/avatars/default.jpg"
            },
            replies: review.replies || []
          };
        });
        
        spotDetail.value.reviews = [...spotDetail.value.reviews, ...formattedReviews];
        hasMoreReviews.value = false;
      } else {
        console.log("加载更多评论API返回数据格式不符合预期");
        hasMoreReviews.value = false;
      }
    } else {
      console.log("加载更多评论API请求返回错误状态码或无数据");
      hasMoreReviews.value = false;
    }
  } catch (error) {
    console.error("加载更多评论失败:", error);
    ElMessage.error("加载更多评论失败");
    hasMoreReviews.value = false;
  }
};

// 快速导航配置
const quickNavs = [
  { id: "intro", title: "景点简介" },
  { id: "info", title: "开放信息" },
  { id: "features", title: "景点特色" },
  { id: "reviews", title: "游客评价" },
];

// 当前激活的导航项
const currentSection = ref("intro");

// 监听滚动，更新当前导航
const updateCurrentSection = () => {
  const sections = quickNavs.map((nav) => document.getElementById(nav.id));
  const scrollPosition = window.scrollY + 100;

  for (let i = sections.length - 1; i >= 0; i--) {
    const section = sections[i];
    if (section && section.offsetTop <= scrollPosition) {
      currentSection.value = quickNavs[i].id;
      break;
    }
  }
};

// 标签类型映射
const getTagType = (tag) => {
  const tagTypes = {
    网红打卡: "danger",
    亲子游玩: "warning",
    自然风光: "success",
    历史文化: "info",
  };
  return tagTypes[tag] || "default";
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 评论相关
const reviewDialogVisible = ref(false);
const showReviewDialog = () => {
  reviewDialogVisible.value = true;
};

// 复制地址
const handleCopyAddress = async () => {
  try {
    await navigator.clipboard.writeText(spotDetail.value.address);
    ElMessage.success("地址已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 获取天气图标
const getWeatherIcon = computed(() => {
  const condition = spotDetail.value.weather?.condition || "晴";
  const weatherIcons = {
    晴: Sunny,
    多云: Cloudy,
    阴: Cloudy,
    小雨: LightRain,
    中雨: HeavyRain,
    大雨: HeavyRain,
    雷阵雨: ThunderstormOne,
    雾: Fog,
    霾: Fog,
    夜间晴: Moon,
    夜间多云: MoonlightCloudy,
    日出: Sunrise,
    日落: Sunset,
  };
  return weatherIcons[condition] || Sunny;
});

// 获取空气质量样式
const getAirQualityClass = computed(() => {
  const quality = spotDetail.value.weather?.airQuality || "优";
  const qualityColors = {
    优: "text-green-500",
    良: "text-blue-500",
    轻度污染: "text-yellow-500",
    中度污染: "text-orange-500",
    重度污染: "text-red-500",
    严重污染: "text-purple-500",
  };
  return qualityColors[quality] || "text-green-500";
});

// 获取附近景点
const getNearbySpots = async () => {
  try {
    const res = await service.get(`/public/spot/nearby/${route.params.id}`);
    console.log("附近景点API响应:", res);
    console.log("响应状态:", res.status);
    console.log("响应数据:", res.data);
    
    // 直接检查res.data是否包含spots数组，适应不同的API响应格式
    if (res.data && (res.data.spots || (res.data.data && res.data.data.spots))) {
      const spotsData = res.data.spots || (res.data.data && res.data.data.spots);
      console.log("处理spots数据:", spotsData);
      
      if (Array.isArray(spotsData) && spotsData.length > 0) {
        console.log("成功处理spots数组数据");
        // 处理spots数组数据
        spotDetail.value.nearbySpots = spotsData.map(spot => ({
          id: spot.id,
          name: spot.name,
          cover: spot.coverImage || spot.cover || "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
          distance: spot.distance,
          category: spot.category,
          price: spot.price,
          rating: spot.rating,
          latitude: spot.latitude,
          longitude: spot.longitude
        }));
      } else {
        console.log("spots数组为空，使用测试数据");
        useTestData();
      }
    } else if (res.data && Array.isArray(res.data)) {
      // 处理直接返回数组的情况
      console.log("API直接返回数组数据");
      spotDetail.value.nearbySpots = res.data.map(spot => ({
        id: spot.id,
        name: spot.name,
        cover: spot.coverImage || spot.cover || "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
        distance: spot.distance,
        category: spot.category,
        price: spot.price,
        rating: spot.rating,
        latitude: spot.latitude,
        longitude: spot.longitude
      }));
    } else {
      console.log("附近景点API返回数据格式不符合预期，使用测试数据");
      console.log("res.data类型:", typeof res.data);
      useTestData();
    }
  } catch (error) {
    console.error("获取附近景点失败:", error);
    useTestData();
  }
};

// 使用测试数据的辅助函数
const useTestData = () => {
  spotDetail.value.nearbySpots = [
    {
      id: 2,
      name: "贵港古镇",
      cover: "https://img1.baidu.com/it/u=413407528,3713955736&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500",
      distance: 3.5,
    }
  ];
};

// 获取景点评论
const getReviews = async () => {
  try {
    const res = await service.get(`/public/spot/reviews/${route.params.id}`, {
      params: {
        page: 1,
        pageSize: 10
      }
    });
    console.log("景点评论API响应:", res);
    
    if (res.data && res.data.code === 200) {
      const apiData = res.data.data;
      
      if (apiData && apiData.records && Array.isArray(apiData.records)) {
        // 确保每条评论都有必要的属性
        spotDetail.value.reviews = apiData.records.map(review => {
          return {
            id: review.id,
            content: review.content || "用户未填写评价内容",
            rating: review.rating || 5,
            createdAt: review.createdAt || review.createTime || new Date().toISOString(),
            likes: review.likes || 0,
            isLiked: review.isLiked || false,
            images: review.images || [],
            location: review.location || "贵港",
            user: {
              id: review.userId || review.user?.id || 0,
              name: review.userName || review.user?.name || "游客",
              avatar: review.userAvatar || review.user?.avatar || "/images/avatars/default.jpg"
            },
            replies: review.replies || []
          };
        });
        spotDetail.value.reviewCount = apiData.total || apiData.records.length;
        hasMoreReviews.value = apiData.total > 10;
      } else if (Array.isArray(apiData)) {
        // 处理数组形式的API数据
        spotDetail.value.reviews = apiData.map(review => {
          return {
            id: review.id,
            content: review.content || "用户未填写评价内容",
            rating: review.rating || 5,
            createdAt: review.createdAt || review.createTime || new Date().toISOString(),
            likes: review.likes || 0,
            isLiked: review.isLiked || false,
            images: review.images || [],
            location: review.location || "贵港",
            user: {
              id: review.userId || review.user?.id || 0,
              name: review.userName || review.user?.name || "游客",
              avatar: review.userAvatar || review.user?.avatar || "/images/avatars/default.jpg"
            },
            replies: review.replies || []
          };
        });
        spotDetail.value.reviewCount = apiData.length;
        hasMoreReviews.value = false;
      } else {
        console.log("景点评论API返回数据格式不符合预期，使用测试数据");
        // 使用测试评论数据
        setTestReviewData();
      }
    } else {
      console.log("景点评论API请求返回错误状态码或无数据，使用测试数据");
      // 使用测试评论数据
      setTestReviewData();
    }
  } catch (error) {
    console.error("获取景点评论失败:", error);
    // 使用测试评论数据
    setTestReviewData();
  }
};

// 设置测试评论数据
const setTestReviewData = () => {
  spotDetail.value.reviews = [
    {
      id: 1,
      content: "环境优美，空气清新，非常适合周末带孩子来玩。",
      rating: 5,
      createdAt: "2023-05-10 10:20:00",
      likes: 23,
      isLiked: false,
      images: [],
      location: "贵港",
      user: {
        id: 101,
        name: "清风徐来",
        avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Felix&backgroundColor=b6e3f4"
      },
      replies: []
    },
    {
      id: 2,
      content: "人不多，景色优美，是休闲的好去处。就是卫生间有点少，建议增加一些。",
      rating: 4,
      createdAt: "2023-05-10 15:40:00",
      likes: 15,
      isLiked: true,
      images: [],
      location: "贵港",
      user: {
        id: 102,
        name: "漫步云端",
        avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Luna&backgroundColor=ffdfbf"
      },
      replies: [
        {
          id: 101,
          content: "同意，上次去卫生间排了好久的队",
          createdAt: "2023-05-11 08:15:00",
          user: {
            id: 103,
            name: "城市观察家",
            avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Max&backgroundColor=d1d4f9"
          }
        }
      ]
    },
    {
      id: 3,
      content: "这里的绿化做得真不错，空气清新，适合早晨来散步，拍了很多美照。",
      rating: 5,
      createdAt: "2023-05-12 07:30:00",
      likes: 42,
      isLiked: false,
      images: ["/images/spots/user-photo1.jpg"],
      location: "南宁",
      user: {
        id: 104,
        name: "光影记录者",
        avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Nova&backgroundColor=c0aede"
      },
      replies: []
    },
    {
      id: 4,
      content: "带着孩子周末来玩，环境不错，就是人有点多，建议错峰出行。",
      rating: 4,
      createdAt: "2023-05-13 14:20:00",
      likes: 18,
      isLiked: false,
      images: [],
      location: "贵港",
      user: {
        id: 105,
        name: "亲子时光",
        avatar: "https://api.dicebear.com/7.x/micah/svg?seed=Avery&backgroundColor=b6e3f4"
      },
      replies: []
    }
  ];
  spotDetail.value.reviewCount = 4;
  hasMoreReviews.value = false;
};

// 获取天气信息
const getWeatherInfo = async () => {
  try {
    // 先获取景点经纬度
    const longitude = spotDetail.value.longitude || 110.279121;
    const latitude = spotDetail.value.latitude || 23.111471;
    
    // 使用Open-Meteo API
    const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min,uv_index_max&timezone=Asia%2FShanghai&forecast_days=1`);
    const data = await response.json();
    
    console.log("Open-Meteo天气信息API响应:", data);
    
    if (data && data.current) {
      // 转换天气代码为中文描述
      const weatherCondition = convertWeatherCode(data.current.weather_code);
      
      // 处理UV指数
      let uvLevel = "低";
      if (data.daily?.uv_index_max) {
        const uv = data.daily.uv_index_max[0];
        if (uv >= 8) uvLevel = "高";
        else if (uv >= 5) uvLevel = "中等";
      }
      
      // 生成天气提示
      const tips = generateWeatherTips(data.current.temperature_2m, data.current.weather_code, data.daily?.uv_index_max?.[0]);
      
      // 更新天气信息
      spotDetail.value.weather = {
        temperature: `${Math.round(data.current.temperature_2m)}°C`,
        condition: weatherCondition,
        airQuality: "优", // Open-Meteo没有提供空气质量数据，需要另外API
        humidity: `${Math.round(data.current.relative_humidity_2m)}%`,
        uvIndex: uvLevel,
        tips: tips
      };
    } else {
      console.log("Open-Meteo API请求无数据，使用默认天气数据");
      // 使用默认天气数据
      spotDetail.value.weather = {
        temperature: "25°C",
        condition: "晴",
        airQuality: "优",
        humidity: "65%",
        uvIndex: "中等",
        tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
      };
    }
  } catch (error) {
    console.error("获取天气信息失败:", error);
    // 使用默认天气数据
    spotDetail.value.weather = {
      temperature: "25°C",
      condition: "晴",
      airQuality: "优",
      humidity: "65%",
      uvIndex: "中等",
      tips: "天气适宜游玩，建议戴好遮阳帽，注意防晒"
    };
  }
};

// 将Open-Meteo天气代码转换为中文描述
const convertWeatherCode = (code) => {
  const weatherMap = {
    0: "晴",
    1: "晴", // 大部分晴朗
    2: "多云", // 部分多云
    3: "阴", // 阴天
    45: "雾",
    48: "霾",
    51: "小雨", // 毛毛雨
    53: "小雨",
    55: "小雨",
    56: "小雨",
    57: "小雨",
    61: "小雨",
    63: "中雨",
    65: "大雨",
    66: "小雨",
    67: "大雨",
    71: "雪", // 小雪
    73: "雪", // 中雪
    75: "雪", // 大雪
    77: "雪",
    80: "小雨", // 小阵雨
    81: "中雨", // 中阵雨
    82: "大雨", // 大阵雨
    85: "雪", // 小阵雪
    86: "雪", // 大阵雪
    95: "雷阵雨",
    96: "雷阵雨",
    99: "雷阵雨"
  };
  return weatherMap[code] || "晴";
};

// 生成天气提示
const generateWeatherTips = (temperature, weatherCode, uvIndex) => {
  let tips = "";
  
  // 根据温度提示
  if (temperature >= 30) {
    tips += "天气炎热，注意防暑降温，建议戴遮阳帽，涂防晒霜；";
  } else if (temperature >= 20) {
    tips += "天气温暖宜人，适合户外活动；";
  } else if (temperature >= 10) {
    tips += "天气较凉，建议穿外套；";
  } else {
    tips += "天气寒冷，请注意保暖；";
  }
  
  // 根据天气状况提示
  if ([0, 1].includes(weatherCode)) {
    if (uvIndex && uvIndex >= 5) {
      tips += "阳光强烈，注意防晒；";
    }
  } else if ([2, 3].includes(weatherCode)) {
    tips += "天空多云，景色宜人；";
  } else if ([51, 53, 55, 56, 57, 61, 80].includes(weatherCode)) {
    tips += "有小雨，建议带伞；";
  } else if ([63, 81].includes(weatherCode)) {
    tips += "有中雨，出行请带伞；";
  } else if ([65, 67, 82].includes(weatherCode)) {
    tips += "有大雨，建议调整出行计划；";
  } else if ([71, 73, 75, 77, 85, 86].includes(weatherCode)) {
    tips += "有雪，注意防滑保暖；";
  } else if ([95, 96, 99].includes(weatherCode)) {
    tips += "有雷阵雨，注意安全，避免在开阔地带停留；";
  } else if ([45, 48].includes(weatherCode)) {
    tips += "能见度较低，注意安全；";
  }
  
  return tips || "天气适宜游玩，祝您游玩愉快！";
};

// 处理公交、自驾等交通信息
const getTransportationInfo = async () => {
  try {
    // 景点名称和地址
    const spotName = spotDetail.value.name;
    const spotAddress = spotDetail.value.address;
    
    // 使用高德地图提供的API密钥
    const amapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
    
    // 准备初始的交通信息数据
    let transportationData = {
      bus: `推荐乘坐前往${spotName}附近的公交线路，详情可咨询当地公交部门`,
      drive: `导航至"${spotName}"，${spotDetail.value.address || "详细位置可咨询景区"}`,
      parking: `${spotName}附近有停车场，建议提前规划`
    };
    
    // 确保transportation对象存在
    if (!spotDetail.value.transportation) {
      spotDetail.value.transportation = transportationData;
    } else {
      // 更新默认值但不覆盖可能已有的数据
      if (!spotDetail.value.transportation.bus) spotDetail.value.transportation.bus = transportationData.bus;
      if (!spotDetail.value.transportation.drive) spotDetail.value.transportation.drive = transportationData.drive;
      if (!spotDetail.value.transportation.parking) spotDetail.value.transportation.parking = transportationData.parking;
    }
    
    // 第一步：获取景点的精确位置坐标（经纬度）
    let longitude = null;
    let latitude = null;
    
    try {
      console.log("尝试通过高德地图API获取景点精确位置");
      
      // 优先使用搜索API获取景点精确位置
      const poiUrl = `https://restapi.amap.com/v3/place/text?key=${amapKey}&keywords=${encodeURIComponent(spotName)}&types=110000&city=&extensions=all`;
      console.log("正在搜索景点POI:", poiUrl);
      
      const poiResponse = await fetch(poiUrl);
      const poiData = await poiResponse.json();
      
      console.log("景点搜索API响应:", poiData);
      
      // 从POI数据中提取经纬度
      if (poiData.status === "1" && poiData.pois?.length > 0) {
        // 找到最匹配的POI点
        const matchingPoi = poiData.pois.find(poi => 
          poi.name.includes(spotName) || spotName.includes(poi.name)
        ) || poiData.pois[0];
        
        if (matchingPoi.location) {
          const location = matchingPoi.location.split(",");
          longitude = parseFloat(location[0]);
          latitude = parseFloat(location[1]);
          
          // 更新景点经纬度
          spotDetail.value.longitude = longitude;
          spotDetail.value.latitude = latitude;
          
          console.log("成功获取景点精确位置:", longitude, latitude);
          
          // 如果POI数据中包含地址信息但景点数据中没有，则更新地址
          if (matchingPoi.address && !spotDetail.value.address) {
            spotDetail.value.address = matchingPoi.address;
          }
        } else {
          console.warn("POI数据中无位置信息");
        }
      } else {
        console.warn("未找到匹配的景点POI");
        
        // 如果POI搜索失败，尝试使用地理编码API作为备选方案
        if (spotAddress) {
          const geocodeUrl = `https://restapi.amap.com/v3/geocode/geo?key=${amapKey}&address=${encodeURIComponent(spotAddress)}`;
          console.log("尝试通过地理编码API获取位置:", geocodeUrl);
          
          const geocodeResponse = await fetch(geocodeUrl);
          const geocodeData = await geocodeResponse.json();
          
          console.log("地理编码API响应:", geocodeData);
          
          if (geocodeData.status === "1" && geocodeData.geocodes?.length > 0) {
            const location = geocodeData.geocodes[0].location.split(",");
            longitude = parseFloat(location[0]);
            latitude = parseFloat(location[1]);
            
            // 更新景点经纬度
            spotDetail.value.longitude = longitude;
            spotDetail.value.latitude = latitude;
            
            console.log("通过地址获取位置成功:", longitude, latitude);
          } else {
            console.warn("地理编码未返回有效数据");
          }
        }
      }
    } catch (locationError) {
      console.error("获取景点位置失败:", locationError);
    }
    
    // 如果获取到了坐标，则进行周边搜索
    if (longitude && latitude) {
      try {
        // 并行处理公交站和停车场的查询
        const [busResult, parkingResult] = await Promise.allSettled([
          // 1. 周边公交站点查询
          (async () => {
            const busStopUrl = `https://restapi.amap.com/v3/place/around?key=${amapKey}&location=${longitude},${latitude}&keywords=公交站&radius=1000&types=150700&extensions=all`;
            console.log("查询周边公交站:", busStopUrl);
            
            const busStopResponse = await fetch(busStopUrl);
            const busStopData = await busStopResponse.json();
            
            console.log("周边公交站响应:", busStopData);
            
            if (busStopData.status === "1" && busStopData.pois?.length > 0) {
              // 提取站点和线路信息
              const busStations = busStopData.pois.slice(0, 3); // 最多取3个最近的站点
              
              // 格式化结果
              return busStations.map(station => {
                const distance = station.distance ? `(${station.distance}米)` : '';
                return `${station.name}${distance}: ${station.address || station.business_area || '途经多路公交'}`;
              }).join("；");
            }
            return null;
          })(),
          
          // 2. 周边停车场查询
          (async () => {
            const parkingUrl = `https://restapi.amap.com/v3/place/around?key=${amapKey}&location=${longitude},${latitude}&keywords=停车场&radius=1000&types=150904&extensions=all`;
            console.log("查询周边停车场:", parkingUrl);
            
            const parkingResponse = await fetch(parkingUrl);
            const parkingData = await parkingResponse.json();
            
            console.log("周边停车场响应:", parkingData);
            
            if (parkingData.status === "1" && parkingData.pois?.length > 0) {
              // 提取停车场信息
              const parkingLots = parkingData.pois.slice(0, 3); // 最多取3个最近的停车场
              
              // 格式化结果
              const parkingInfo = parkingLots.map(lot => {
                const distance = lot.distance ? `(${lot.distance}米)` : '';
                return `${lot.name}${distance}`;
              }).join("；");
              
              if (parkingInfo) {
                return parkingInfo + "；收费标准请以现场为准";
              }
            }
            return null;
          })()
        ]);
        
        // 处理公交查询结果
        if (busResult.status === 'fulfilled' && busResult.value) {
          spotDetail.value.transportation.bus = busResult.value;
          console.log("更新公交信息:", busResult.value);
        }
        
        // 处理停车场查询结果
        if (parkingResult.status === 'fulfilled' && parkingResult.value) {
          spotDetail.value.transportation.parking = parkingResult.value;
          console.log("更新停车场信息:", parkingResult.value);
        }
        
        // 3. 处理自驾路线信息
        try {
          // 城市名称，用于自驾路线提示
          const cityName = spotDetail.value.city || "贵港市";
          
          // 计算从市中心到景点的预估时间和距离
          // 理想情况下应调用路径规划API，这里简化处理
          const distance = Math.ceil(Math.random() * 5 + 2); // 模拟距离
          const duration = Math.ceil(Math.random() * 20 + 10); // 模拟时间
          
          // 格式化自驾路线信息
          const driveInfo = `导航至"${spotName}"，${spotDetail.value.address || ""}。从${cityName}市区出发约${distance}公里，驾车约${duration}分钟。`;
          
          // 更新自驾信息
          spotDetail.value.transportation.drive = driveInfo;
          console.log("更新自驾信息:", driveInfo);
        } catch (driveError) {
          console.error("处理自驾信息失败:", driveError);
        }
      } catch (searchError) {
        console.error("周边搜索失败:", searchError);
      }
    } else {
      console.warn("未获取到景点坐标，无法进行周边搜索");
    }
  } catch (error) {
    console.error("获取交通信息失败:", error);
  }
};

// 添加在高德地图中打开的功能 - 使用景点名称搜索
const openInMap = () => {
  const spotName = encodeURIComponent(spotDetail.value.name);
  const address = encodeURIComponent(spotDetail.value.address || "");
  
  // 优先使用经纬度定位（如果有）
  if (spotDetail.value.longitude && spotDetail.value.latitude) {
    const longitude = spotDetail.value.longitude;
    const latitude = spotDetail.value.latitude;
    
    // 使用经纬度构建高德地图URL
    const amapUrl = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${spotName}&src=myapp&coordinate=gaode&callnative=0`;
    
    // 在新窗口中打开高德地图
    window.open(amapUrl, '_blank');
  } else {
    // 如果没有经纬度，直接使用景点名称搜索
    const searchUrl = `https://uri.amap.com/search?keyword=${spotName}&src=myapp`;
    
    // 在新窗口中打开高德地图搜索结果
    window.open(searchUrl, '_blank');
  }
};

onMounted(() => {
  window.addEventListener("scroll", updateCurrentSection);
  getSpotDetail();
});

onUnmounted(() => {
  window.removeEventListener("scroll", updateCurrentSection);
});
</script>

<style lang="scss" scoped>
.spot-detail {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .spot-hero {
    @apply bg-gray-50 dark:bg-gray-800 py-8;

    .hero-carousel {
      :deep(.el-carousel__item) {
        @apply h-full;

        .el-image {
          @apply w-full h-full object-cover;
        }
      }

      :deep(.el-carousel__indicators) {
        @apply bottom-4;
      }
    }
  }

  .spot-info-card {
    @apply transition-shadow hover:shadow-xl dark:shadow-gray-800;
  }

  .section-header {
    @apply flex items-center mb-4;

    .section-title {
      @apply text-xl font-medium text-gray-900 dark:text-white;
    }
  }

  .content-section {
    @apply scroll-mt-20;
  }

  .quick-nav {
    .nav-item {
      @apply px-4 py-2 text-sm font-medium transition-colors relative no-underline;

      &::after {
        content: "";
        @apply absolute bottom-0 left-0 w-full h-0.5 bg-primary-600 transform scale-x-0 transition-transform;
      }

      &.active {
        @apply text-primary-600 dark:text-primary-400;

        &::after {
          @apply scale-x-100;
        }
      }
    }
  }

  .info-card {
    @apply transition-shadow hover:shadow-md dark:shadow-gray-800 border border-gray-100 dark:border-gray-700;
  }

  .feature-card {
    @apply transition-all hover:-translate-y-1 hover:shadow-md dark:shadow-gray-800;
  }

  .nearby-item {
    @apply p-2 rounded-lg transition-colors hover:bg-gray-50 dark:hover:bg-gray-700;
  }

  .ticket-item {
    @apply transition-all hover:-translate-y-0.5;
  }

  .weather-info {
    .weather-icon {
      @apply shadow-lg transform transition-transform duration-300;

      &:hover {
        @apply -translate-y-1;
      }
    }

    .weather-meta-item {
      @apply transition-colors duration-200 hover:bg-gray-100 dark:hover:bg-gray-600;
    }
  }

  :deep(.el-dialog) {
    @apply dark:bg-gray-800;

    .el-dialog__title {
      @apply dark:text-white;
    }

    .el-dialog__body {
      @apply dark:text-gray-300;
    }
  }

  :deep(.el-rate) {
    .el-rate__icon {
      @apply dark:text-gray-600;

      &.hover {
        @apply dark:text-primary-400;
      }

      &.is-active {
        @apply dark:text-primary-400;
      }
    }
  }

  :deep(.el-progress) {
    .el-progress-bar__outer {
      @apply dark:bg-gray-700;
    }

    .el-progress-bar__inner {
      @apply dark:bg-primary-500;
    }

    .el-progress__text {
      @apply dark:text-gray-300;
    }
  }

  :deep(.time-chart) {
    .chart-legend {
      @apply dark:text-gray-300;
    }

    .chart-grid {
      @apply dark:border-gray-700;
    }

    .chart-bar {
      &.舒适 {
        @apply dark:bg-green-500;
      }
      &.适中 {
        @apply dark:bg-yellow-500;
      }
      &.拥挤 {
        @apply dark:bg-red-500;
      }
    }

    .time-label {
      @apply dark:text-gray-400;
    }
  }

  // 添加评论操作按钮样式
  :deep(.comment-item) {
    .action-btn {
      @apply py-1 px-2 rounded-md transition-colors duration-200 flex items-center;
      
      &:hover {
        @apply bg-gray-100 dark:bg-gray-700 text-primary-600 dark:text-primary-400;
      }
    }
    
    .arco-btn {
      @apply text-sm px-3 py-1 rounded-md text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-700;
      
      &:hover {
        @apply text-primary-600 dark:text-primary-400 bg-gray-200 dark:bg-gray-600;
      }
      
      .arco-icon {
        @apply mr-1;
      }
    }
  }
}
</style>
